import * as vscode from "vscode";
import { logger } from "./logger";

let exec = vscode.commands.executeCommand;

// 真正的删除所有其他窗口
function deleteOtherWindow(): void {
  exec("workbench.action.closeEditorsInOtherGroups");
  // exec("workbench.action.activityBarLocation.hide");
  exec("workbench.action.closeSidebar");
  exec("workbench.action.closePanel");
}

// 进入选择状态
var inMarkMode = false;
function setMarkCommand(): void {
  logger.info("set mark command");
  logger.info(vscode.window.activeTextEditor?.selections);
}

function windowMoveUp(): void {
  exec("workbench.action.focusAboveGroup");
}

function windowMoveDown(): void {
  exec("workbench.action.focusBelowGroup");
}

function windowMoveLeft(): void {
  exec("workbench.action.focusLeftGroup");
}

function windowMoveRight(): void {
  exec("workbench.action.focusRightGroup");
}

export function saveBuffer(): void {
  exec("workbench.action.files.save").then(
    () => {
      let msg = "文件已保存";
      // logger.info(msg);
      vscode.window.setStatusBarMessage(msg, 1000);
    },
    (fail: any) => {
      logger.info("save failed");
      logger.info(fail);
    }
  );
}

let baseCommandMap = new Map([
  ["forward-char", () => exec("cursorRight")],
  ["next-line", () => exec("cursorDown")],
  ["backward-char", () => exec("cursorLeft")],
  ["previous-line", () => exec("cursorUp")],
  ["beginning-of-line", () => exec("cursorHome")],
  ["end-of-line", () => exec("cursorEnd")],
  ["delete-char", () => exec("deleteRight")],
  ["switch-buffer", () => exec("workbench.action.showAllEditors")],
  ["save-buffers-kill-terminal", () => exec("workbench.action.quit")],
  ["keyboard-quit", () => {}], // FIXME 暂时没有
  ["split-window-vertically", () => exec("workbench.action.splitEditor")],
  [
    "split-window-horizontally",
    () => exec("workbench.action.splitEditorOrthogonal"),
  ],
  ["delete-other-windows", deleteOtherWindow],
  ["save-buffer", saveBuffer],
  ["delete-window", () => exec("workbench.action.closeActiveEditor")],
  ["set-mark-command", setMarkCommand],
  ["windmove-left", windowMoveLeft],
  ["windmove-right", windowMoveRight],
  ["windmove-up", windowMoveUp],
  ["windmove-down", windowMoveDown],
  ["xref-find-definitions", () => exec("editor.action.revealDefinition")],
  ["xref-go-back", () => exec("workbench.action.navigateBack")]
]);

export function baseOperationInit(context: vscode.ExtensionContext): void {
  for (const [cmd, op] of baseCommandMap) {
    let d = vscode.commands.registerCommand("vemacs.base." + cmd, op);
    context.subscriptions.push(d);
  }
}
